
#include "type.h"
#include "button_config.h"

#ifndef BUTTON_NUM_MAX
#error "BUTTON_NUM_MAX NOT HAVE A CONFIG VALUE"
#endif
#ifndef BUTTON_PRESS_LEVEL
#error "BUTTON_PRESS_LEVEL NOT HAVE A CONFIG VALUE"
#endif
#ifndef BUTTON_JITTER_TICK
#error "BUTTON_JITTER_TICK NOT HAVE A CONFIG VALUE"
#endif
#ifndef BUTTON_LONG_PRESS_TICK
#error "BUTTON_LONG_PRESS_TICK NOT HAVE A CONFIG VALUE"
#endif
#ifndef BUTTON_LONG_PRESS_REPEAT_TICK
#error "BUTTON_LONG_PRESS_REPEAT_TICK NOT HAVE A CONFIG VALUE"
#endif

#define BUTTON_RELEASE_LEVEL  (!BUTTON_PRESS_LEVEL)

typedef struct {
	volatile uint16_t button_press_count;
	volatile uint8_t button_last_pin_level;
} BUTTON_STRUCT;

static volatile BUTTON_STRUCT BUTTONS[BUTTON_NUM_MAX];

void button_init(void)
{
	volatile uint8_t i;
	for(i = 0; i < BUTTON_NUM_MAX; i++) {
		BUTTONS[i].button_press_count = 0;
		BUTTONS[i].button_last_pin_level = BUTTON_RELEASE_LEVEL;
	}
}

void button_scan_handler(void)
{
	volatile uint8_t temp_button_pin_level;
	volatile uint8_t i;
	for (i = 0; i < BUTTON_NUM_MAX; i++) {
		temp_button_pin_level = button_read_pin_level_config(i);
		if(BUTTONS[i].button_last_pin_level == BUTTON_RELEASE_LEVEL){
			if(temp_button_pin_level == BUTTON_RELEASE_LEVEL){
				BUTTONS[i].button_press_count = 0;
				button_free_event(i);
			}
			else{
			  	if(BUTTONS[i].button_press_count == 0){
					button_press_event(i);
				}
				BUTTONS[i].button_press_count++;
			}
		}
		else{
			if(temp_button_pin_level == BUTTON_RELEASE_LEVEL){
#if (BUTTON_JITTER_TICK > 0)
				if(BUTTONS[i].button_press_count >= BUTTON_JITTER_TICK){
#endif
						button_release_event(i);
#if (BUTTON_JITTER_TICK > 0)
				}
#endif
				BUTTONS[i].button_press_count = 0;
			}
			else{
				BUTTONS[i].button_press_count++;
				if(BUTTONS[i].button_press_count == BUTTON_LONG_PRESS_TICK){
					button_long_press_event(i);
				}
				else if(BUTTONS[i].button_press_count >= BUTTON_LONG_PRESS_TICK + BUTTON_LONG_PRESS_REPEAT_TICK){
					button_long_press_repeat_event(i);
					BUTTONS[i].button_press_count = BUTTON_LONG_PRESS_TICK;
				}
			}
		}
		BUTTONS[i].button_last_pin_level = temp_button_pin_level;
	}
}

//press 1; release 0
bool_t button_read_press_release(uint8_t button_mun)
{
	if(button_mun < BUTTON_NUM_MAX){
		return (button_read_pin_level_config(button_mun) == BUTTON_PRESS_LEVEL);
	}
	else{
		return BUTTON_RELEASE_LEVEL;
	}
}

bool_t button_all_release(void)
{
	volatile uint8_t i;
	volatile bool_t ret = 1;

	for (i = 0; i < BUTTON_NUM_MAX; i++) {
		if(button_read_pin_level_config(i) != BUTTON_RELEASE_LEVEL){
			ret = 0;
			break;
		}
	}

	return ret;
}

